#!/usr/bin/env python

import time
import datetime

def call_on_clock_minute(tick):
    """Invoke the callable, tick, every clock minute(with about 1 second
    precision).

    tick will be called like this: tick(t), where t is the time of the minute.

    tick should return as soon as possible to avoid delaying the execution of
    the next clock-minute tick. Preferably, tick will start its work in a
    separate thread.
    """
    now = datetime.datetime.now()
    delta = 60 - (now.second + now.microsecond/1000000.0)
    next_minute = now + datetime.timedelta(seconds=delta)
    assert next_minute.seconds == 0 and next_minute.microseconds == 0
    while True:
        time.sleep(1 if delta < 1 else delta)
        now = datetime.datetime.now()
        if now >= next_minute:
            tick(next_minute)
            next_minute = next_minute + datetime.timedelta(minutes=1)
        delta = 60 - (now.second + now.microsecond/1000000.0)


